/*
Write function scramble(str1,str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.

For example:
str1 is 'rkqodlw' and str2 is 'world' the output should return true.
str1 is 'cedewaraaossoqqyt' and str2 is 'codewars' should return true.
str1 is 'katas' and str2 is 'steak' should return false.

Only lower case letters will be used (a-z). No punctuation or digits will be included.
Performance needs to be considered
*/

function getCountObj(text) {
    let obj = {};
    const len = text.length;
    for (let i = 0; i < len; ++i) {
        let ch = text[i];
        let count = obj[ch];
        if (!count) count = 0;
        count++;
        obj[ch] = count;
    }
    return obj;
}

function scramble(str1, str2) {
    let obj1 = getCountObj(str1);
    let obj2 = getCountObj(str2);
    console.log(obj1);
    console.log(obj2);
    let flag = true;
    for (let k in obj2) {
        if (obj1[k] === undefined) {
            flag = false;
            break;
        } else if (obj2[k] > obj1[k]) {
            flag = false;
            break;
        }
    }
    return flag;
}


//a good kata, but slower than mine

function scramble(str1, str2) {
    var map = {};
    for (var i in str1) {
        map[str1[i]] ? map[str1[i]]++ : map[str1[i]] = 1;
    }
    for (var i in str2) {
        if (!map[str2[i]]) return false;
        map[str2[i]]--;
    }
    return true;
}